package com.raylu.day02basic;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

// 说明并行度的设置
public class Example1ParallelismSet {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 设置全局并行度为1
        // 如果某个算子没有设置并行度，那么这个算子的并行度是1
        env.setParallelism(1);

        env
                .socketTextStream("localhost", 9999)
                .setParallelism(1) // 表示source算子必须只能占用1个任务插槽
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] arr = value.split(" ");
                        for (String word : arr) {
                            out.collect(Tuple2.of(word, 1));
                        }
                    }
                })
                .setParallelism(2) // 表示flatMap算子必须要占用两个任务插槽
                .keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
                    @Override
                    public String getKey(Tuple2<String, Integer> value) throws Exception {
                        return value.f0;
                    }
                })
                .sum("f1")
                .setParallelism(4) // 表示sum算子必须占用4个任务插槽
                .print()
                .setParallelism(1); // 表示print算子占用1个任务插槽

        env.execute();
    }
}
